package org.artifact.core.plugin.netty.codec;

import java.nio.ByteBuffer;

import org.artifact.core.context.bytebuf.IByteBuff;
import org.artifact.core.context.bytebuf.NettyByteBuf;
import org.artifact.core.context.packet.IPacket;
import org.artifact.core.context.session.ISession;
import org.artifact.core.plugin.netty.handler.NettyHandler;
import org.artifact.core.plugin.netty.packet.NettyPacketUtil;
import org.artifact.core.plugin.netty.session.NettySessionAttrEnum;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.Attribute;

public class NettyEncoder extends MessageToByteEncoder<IPacket> {

	@Override
	protected void encode(ChannelHandlerContext ctx, IPacket packet, ByteBuf out) throws Exception {
		// 使用IByteBuff代理out
		out.markWriterIndex();
		
		int packetLength = 0;
		short checkSum = 0;
		out.writeInt(0);
		out.writeShort(0);

		// 压缩代理
		IByteBuff byteBuff = new NettyByteBuf(out);
		// 写入包体
		packet.forByteBuff(byteBuff);

		
		packetLength = out.readableBytes();
		int lastWriterIndex  = byteBuff.getWriterIndex();
		
		out.resetWriterIndex();
		
		checkSum = NettyPacketUtil.sumCheck(out, 6, packetLength - 6);
		byteBuff.writeInt(packetLength);
		byteBuff.writeShort(checkSum);
		byteBuff.setWriterIndex(lastWriterIndex );
		
		// 加密
		Attribute<ISession> attach = ctx.channel().attr(NettyHandler.SESSION);
		int[] encryptKeys = attach.get().getAttr(NettySessionAttrEnum.ENCRYPT_KEY_SECRET);
		NettyPacketUtil.encrypt(out, encryptKeys, 4, packetLength - 4);
	}

}
